package com.atguigu.tingshu.order.context;

import com.atguigu.tingshu.order.strategy.OrderTradeStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

// 策略上下文对象，管理所有的策略实现类
@Component
@Slf4j
public class OrderTradeStrategyContext implements ApplicationContextAware {

    // 在该Map中存储所有的策略对象
    private static final Map<String , OrderTradeStrategy> TRADE_INFO_STRATGY_MAP = new ConcurrentHashMap<>();

    // 定义从Map中获取具体策略对象的方法
    public static OrderTradeStrategy getOrderTradeStrategy(String itemType) {
        return TRADE_INFO_STRATGY_MAP.get(itemType) ;
    }

    // 从Spring容器中获取所有的策略实现类对象，将其存储到Map对象
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, OrderTradeStrategy> strategyMap = applicationContext.getBeansOfType(OrderTradeStrategy.class);
        strategyMap.values().forEach(orderTradeStrategy -> {
            TRADE_INFO_STRATGY_MAP.put(orderTradeStrategy.getItemType() , orderTradeStrategy) ;
        });
    }

}